package cn.mania_man.trpg_helper_server.room;

import cn.mania_man.trpg_helper_server.util.ReqTypeEnum;
import cn.mania_man.trpg_helper_server.util.ResTypeEnum;
import cn.mania_man.trpg_helper_server.util.ResponseUtil;
import cn.mania_man.trpg_helper_server.websocket.MessageSender;
import cn.mania_man.trpg_helper_server.websocket.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.stream.Collectors;

public class RequestMessage {
    private String body;
    private ReqTypeEnum type;
    private String receiver;
    private String msgId;

    public RequestMessage(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        try {
            this.setType(ReqTypeEnum.valueOf(jsonObject.getString("type")));
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("错误的type，无法解析request");
        }
        this.setBody(jsonObject.getString("body"));
        this.setReceiver(jsonObject.getString("receiver"));
        this.setMsgId(jsonObject.getString("msgId"));
    }

    public void handle(User sender) {
        if (type !=ReqTypeEnum.recognize_message){
            LoggerFactory.getLogger(RequestMessage.class).info("处理了来自用户:"+sender.getUserName()+"的"+type+"请求");
        }
        switch (getType()) {
            case get_init_data: {
                ResponseMessage res = new ResponseMessage();
                res.addReceiver("role:compare", sender.getRoom(), false);
                res.setType(ResTypeEnum.need_init_data);
                res.getSenderRole().add(sender.getUserName());
                res.ignoreUser(sender);
                MessageSender.PushMessage(res);
                break;
            }
            case post_init_data: {
                ResponseMessage res = new ResponseMessage(this.body, sender, ResTypeEnum.send_init_data);
                res.addSender("compare");
                res.addReceiver(this.receiver, sender.getRoom(),true);
                res.ignoreUser(sender);
                MessageSender.PushMessage(res);
                break;
            }
            case post_user_role: {
                JSONObject jsonObject = JSON.parseObject(body);
                String target = jsonObject.getString("target");
                JSONArray roleList =jsonObject.getJSONArray("role");
                String[] role = new String[roleList.size()];
                for (int i = 0; i < roleList.size(); i++) {
                    role[i]=roleList.getString(i);
                }
                sender.getRoom().getUsers().stream().filter(user -> user.getUserName().equals(target))
                        .findFirst().ifPresent(user -> user.setRole(Arrays.stream(role)
                                .collect(Collectors.toSet())));
                MessageSender.PushMessage(ResponseUtil.forward(this,sender,ResTypeEnum.send_user_role));
                break;
            }
            case self_author: {
                if (sender.getRoom().getPassword().equals(body)) {
                    MessageSender.PushMessage(ResponseUtil.massage(sender.getUserName() + "提升自己的权限为主持人", "*", sender.getRoom()));

                    if(sender.getRoom().getUsers().stream().noneMatch(user -> user.getRole().contains("compare"))){
                        sender.getRole().add("compare");
                        ResponseMessage res = new ResponseMessage();
                        res.addReceiver("role:compare", sender.getRoom(), false);
                        res.setType(ResTypeEnum.need_init_data);
                        res.getSenderRole().add("*");
                        res.ignoreUser(sender);
                    }else {
                        sender.getRole().add("compare");
                        JSONObject jo = new JSONObject();
                        jo.put("target", sender.getUserName());
                        jo.put("role", sender.getRole());
                        ResponseMessage res = new ResponseMessage(jo.toJSONString(), sender, ResTypeEnum.send_user_role);
                        res.addReceiver("*", sender.getRoom(), false);
                        MessageSender.PushMessage(res);
                    }
                } else {
                    MessageSender.PushMessage(ResponseUtil.massage("获取权限失败：密码错误", "name:" + sender.getUserName(), sender.getRoom()));
                }
                break;
            }
            case post_element_data:{
                MessageSender.PushMessage(ResponseUtil.forward(this,sender,ResTypeEnum.send_element_data));
                //TODO log相关
                break;
            }
            case recognize_message:{
                MessageSender.finishMessage(this.body,sender);
                break;
            }
            case post_cardtype_data:{
                MessageSender.PushMessage(ResponseUtil.forward(this,sender,ResTypeEnum.send_cardtype_data));
                break;
            }
            case post_room_role:{
                MessageSender.PushMessage(ResponseUtil.forward(this,sender,ResTypeEnum.send_room_role));
                break;
            }
        }
        if(getType()!=ReqTypeEnum.recognize_message){
            ResponseMessage res = new ResponseMessage();
            res.setBody(this.getMsgId());
            res.setType(ResTypeEnum.recognize_message);
            res.getReceivers().add(sender);
            res.send();
        }
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public ReqTypeEnum getType() {
        return type;
    }

    public void setType(ReqTypeEnum type) {
        this.type = type;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getMsgId() {
        return msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }
}
